package 书店销售管理系统;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import redis.clients.jedis.Jedis;

public class UserManagement extends JFrame {
    private static final long serialVersionUID = 1L;

    private JTable table;
    private DefaultTableModel model;

    private Jedis jedis = new Jedis("localhost", 6379); // 连接本地 Redis 服务器，默认端口号为 6379

    public UserManagement() {
        setTitle("用户信息管理");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900, 700);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 设置背景
        JPanel background = new JPanel() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 绘制半透明粉色背景
                g.setColor(new Color(255, 192, 203, 128));
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        add(background, BorderLayout.CENTER);

        // 创建顶部面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        topPanel.setOpaque(false); // 设置为透明背景

        // 添加菜单栏和下拉菜单
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu dropDownMenu = new JMenu("菜单");
        menuBar.add(dropDownMenu);
        JMenuItem salesItem = new JMenuItem("销售信息管理");
        salesItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new SalesManagement().setVisible(true);
            }
        });
        dropDownMenu.add(salesItem);
        JMenuItem bookItem = new JMenuItem("图书信息管理");
        bookItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Book().setVisible(true);
            }
        });
        dropDownMenu.add(bookItem);
        JMenuItem memberItem = new JMenuItem("会员信息管理");
        memberItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new MemberManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem);
        JMenuItem memberItem1 = new JMenuItem("会员类别管理");
        memberItem1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new VipTypeManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem1);
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭窗口
                System.exit(0); // 退出应用程序
            }
        });
        dropDownMenu.add(exitItem);

        // 添加按钮：添加、编辑、删除、查询
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UserDialog dialog = new UserDialog(UserManagement.this, "Add User", null);
                if (dialog.isOK()) {
                    addUser(dialog.getData());
                }
            }
        });
        topPanel.add(addButton);

        JButton editButton = new JButton("Edit");
        editButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String username = (String) model.getValueAt(row, 0);
                    Object[] data = { username, model.getValueAt(row, 1) };
                    UserDialog dialog = new UserDialog(UserManagement.this, "Edit User", data);
                    if (dialog.isOK()) {
                        editUser(dialog.getData());
                    }
                } else {
                    JOptionPane.showMessageDialog(UserManagement.this, "Please select a user to edit.");
                }
            }
        });
        topPanel.add(editButton);

        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String username = (String) model.getValueAt(row, 0);
                    int result = JOptionPane.showConfirmDialog(UserManagement.this,
                            "Are you sure you want to delete user \"" + username + "\"?", "Delete User",
                            JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        deleteUser(username);
                    }
                } else {
                    JOptionPane.showMessageDialog(UserManagement.this, "Please select a user to delete.");
                }
            }
        });
        topPanel.add(deleteButton);

        JTextField searchField = new JTextField(20);
        searchField.setHorizontalAlignment(JTextField.CENTER); // 设置文本框居中对齐
        searchField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchUser(searchField.getText());
            }
        });
        topPanel.add(searchField);

        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchUser(searchField.getText());
            }
        });
        topPanel.add(searchButton);

        // 添加顶部面板
        background.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = { "用户名", "密码" };
        model = new DefaultTableModel(columnNames, 0) {
            private static final long serialVersionUID = 1L;

            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);
        table.setPreferredScrollableViewportSize(new Dimension(600, 400));
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        background.add(scrollPane, BorderLayout.CENTER);

        refreshTable(); // 刷新表格
        setVisible(true);
    }

    private void refreshTable() {
        model.setRowCount(0); // 清空表格数据
        TreeMap<String, String> users = new TreeMap<>(jedis.hgetAll("USER1")); // 获取 Redis 中存储的所有用户信息
        for (String username : users.keySet()) {
            String password = users.get(username);
            model.addRow(new Object[] { username, password });
        }
    }

    private void addUser(Object[] data) {
        String username = data[0].toString();
        String password = data[1].toString();
        jedis.hset("USER1", username, password); // 使用 hash 类型存储用户信息
        refreshTable(); // 添加成功后刷新表格
    }

    private void editUser(Object[] data) {
        String username = data[0].toString();
        TreeMap<String, String> users = new TreeMap<>(jedis.hgetAll("USER1")); // 获取 Redis 中存储的所有用户信息
        if (users.containsKey(username)) {
            String password = data[1].toString();
            jedis.hset("USER1", username, password); // 使用 hash 类型更新用户信息
            refreshTable(); // 修改成功后刷新表格
        } else {
            JOptionPane.showMessageDialog(UserManagement.this, "User \"" + username + "\" not found.");
        }
    }

    private void deleteUser(String username) {
        Long result = jedis.hdel("USER1", username); // 使用 hdel 命令删除指定用户
        if (result > 0) {
            refreshTable(); // 删除成功后刷新表格
        } else {
            JOptionPane.showMessageDialog(UserManagement.this, "User \"" + username + "\" not found.");
        }
    }

    private void searchUser(String keyword) {
        model.setRowCount(0); // 清空表格数据
        TreeMap<String, String> users = new TreeMap<>(jedis.hgetAll("USER1")); // 获取 Redis 中存储的所有用户信息
        for (String username : users.keySet()) {
            if (username.toUpperCase().contains(keyword.toUpperCase())) {
                String password = users.get(username);
                model.addRow(new Object[] { username, password });
            }
        }
    }

    private class UserDialog extends JDialog {
        private static final long serialVersionUID = 1L;
        private JTextField usernameField;
        private JPasswordField passwordField;
        private boolean isOK;

        public UserDialog(JFrame parent, String title, Object[] data) {
            super(parent, title, true); // 模态对话框
            setSize(300, 200);
            setLocationRelativeTo(null);
            setResizable(false);
            setLayout(new BorderLayout());

            JPanel panel = new JPanel(new GridLayout(2, 2, 5, 10));
            panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            JLabel usernameLabel = new JLabel("UNO:");
            panel.add(usernameLabel);

            usernameField = new JTextField();
            panel.add(usernameField);

            JLabel passwordLabel = new JLabel("Password:");
            panel.add(passwordLabel);

            passwordField = new JPasswordField();
            panel.add(passwordField);

            add(panel, BorderLayout.CENTER);

            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

            JButton okButton = new JButton("OK");
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    isOK = true;
                    dispose();
                }
            });
            buttonPanel.add(okButton);

            JButton cancelButton = new JButton("Cancel");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                }
            });
            buttonPanel.add(cancelButton);

            add(buttonPanel, BorderLayout.SOUTH);

            if (data != null) { // 如果是编辑用户，则将原有数据填充到对话框中
                usernameField.setText(data[0].toString());
                passwordField.setText(data[1].toString());
            }

            setVisible(true);
        }

        public Object[] getData() {
            Object[] data = { usernameField.getText(), new String(passwordField.getPassword()) };
            return data;
        }

        public boolean isOK() {
            return isOK;
        }
    }
    public static void main(String[] args) { // 连接 
    	 new UserManagement();
    
    	}
    }